package cn.cosmosx.base.constant;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 特殊处理接口地址枚举
 */
public enum AuthSwitch {
    /**
     * 可匿名访问url列表（swagger）
     */
    SWAGGER("/doc.html**", "/webjars/**", "/v3/api-docs/**", "/v2/api-docs/**", "/swagger-resources/**", "/**/favicon.ico**"),

    /**
     * 白名单url列表（非鉴权接口）
     */
    WHITE_LIST("/sys/user/login", "/error", "/calc/**", "/test/**", "/cash/flow/**", "/sys/generate/**"),

    /**
     * 登录后可访问的接口
     */
    AUTHED_LIST("/sys/user/logout", "/sys/user/get"),

    /**
     * 黑名单url列表
     */
    BLACK_LIST(),
    ;
    private final String[] urls;

    AuthSwitch(String... urls) {
        this.urls = urls;
    }

    public String[] get() {
        return urls;
    }

    /**
     * 白名单
     */
    public static boolean matchWhiteList(HttpServletRequest request) {
        return matches(request, SWAGGER.get()) || matches(request, WHITE_LIST.get());
    }

    /**
     * 登录可访问
     */
    public static boolean matchAuthedList(HttpServletRequest request) {
        return matches(request, AUTHED_LIST.get());
    }

    /**
     * 白名单权限
     */
    public static String[] getWhiteList() {
        List<String> urls = new ArrayList<String>(Arrays.asList(SWAGGER.get()));
        urls.addAll(Arrays.asList(WHITE_LIST.get()));
        return urls.toArray(new String[0]);
    }

    /**
     * ANT模式匹配URL路径
     *
     * @param request - 请求
     * @param urls    - url地址
     */
    public static boolean matches(HttpServletRequest request, String... urls) {
        return Arrays.stream(urls).anyMatch(x -> new AntPathRequestMatcher(x).matches(request));
    }

    public static String getRequestPath(HttpServletRequest request) {
        String url = request.getServletPath();
        String pathInfo = request.getPathInfo();
        if (pathInfo != null) {
            url = StringUtils.isNoneEmpty(url) ? url + pathInfo : pathInfo;
        }
        return url;
    }
}